package com.hxzy.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.rabbit.constant.MqConst;
import com.hxzy.common.rabbit.service.RabbitService;
import com.hxzy.yygh.common.exception.YyghException;
import com.hxzy.yygh.common.helper.HttpRequestHelper;
import com.hxzy.yygh.common.result.ResultCodeEnum;
import com.hxzy.yygh.enums.OrderStatusEnum;
import com.hxzy.yygh.enums.PaymentStatusEnum;
import com.hxzy.yygh.enums.PaymentTypeEnum;
import com.hxzy.yygh.hosp.client.HospitalFeignClient;
import com.hxzy.yygh.model.order.OrderInfo;
import com.hxzy.yygh.model.order.PaymentInfo;
import com.hxzy.yygh.model.user.Patient;
import com.hxzy.yygh.order.mapper.OrderMapper;
import com.hxzy.yygh.order.service.OrderService;
import com.hxzy.yygh.order.service.PaymentService;
import com.hxzy.yygh.order.service.WeixinService;
import com.hxzy.yygh.user.client.PatientFeignClient;
import com.hxzy.yygh.vo.hosp.ScheduleOrderVo;
import com.hxzy.yygh.vo.msm.MsmVo;
import com.hxzy.yygh.vo.order.*;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper,OrderInfo> implements OrderService {

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private WeixinService weixinService;

    //生成挂号订单
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //获取就诊人信息
        Patient patient = patientFeignClient.getPatient(patientId);

        //获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);

            //判断当前时间是否还可以预约
            if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()){
                throw new YyghException(ResultCodeEnum.TIME_NO);
            }

        //获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        //新建OrderInfo对象
        OrderInfo orderInfo = new OrderInfo();
            //属性拷贝到orderInfo
            BeanUtils.copyProperties(scheduleOrderVo, orderInfo);

        //封装其他属性到orderInfo
            String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);
            orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
            orderInfo.setUserId(patient.getUserId());
            orderInfo.setPatientId(patientId);
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //将预约信息保存到数据库中
        baseMapper.insert(orderInfo);

        //设置调用医院接口所以要的参数，并将参数放到map集合中
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());

        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);

        //调用医院预约接口，并返回一个结果
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl()+"/order/submitOrder");

        //判断返回状态
        if (result.getInteger("code") == 200){
            //获取返回订单数据
            JSONObject jsonObject = result.getJSONObject("data");
                //预约记录唯一标识
                String hosRecordId = jsonObject.getString("hosRecordId");
                //预约序号
                Integer number = jsonObject.getInteger("number");
                //取号时间
                String fetchTime = jsonObject.getString("fetchTime");
                //取号地址
                String fetchAddress = jsonObject.getString("fetchAddress");

            //封装属性
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);

            //执行更新订单方法
            baseMapper.updateById(orderInfo);


            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //发送mq信息更新号源和短信通知
                //更新号源属性封装到OrderMqVo
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(scheduleId);
                orderMqVo.setReservedNumber(reservedNumber);
                orderMqVo.setAvailableNumber(availableNumber);
                //短信通知属性封装
                    MsmVo msmVo = new MsmVo();
                    //封装电话号码
                    msmVo.setPhone(orderInfo.getPatientPhone());
                    //封装短信模板
                    msmVo.setTemplateCode("SMS_460665428");
                    //处理其他参数
                        String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                                        + (orderInfo.getReserveTime()==0 ? "上午": "下午");

                        Map<String,Object> param = new HashMap<String,Object>(){{
                            put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                            put("amount", orderInfo.getAmount());
                            put("reserveDate", reserveDate);
                            put("name", orderInfo.getPatientName());
                            put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
                        }};
                    //封装其他参数
                    msmVo.setParam(param);
                //封装短信对象到OrderMqVo
                orderMqVo.setMsmVo(msmVo);
                //发送rabbitMQ消息,完成更新号源即短信发送
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        }else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    //根据订单id查询订单详情
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return this.packOrderInfo(orderInfo);
    }

    //订单列表功能
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //获取条件值
        String keyword = orderQueryVo.getKeyword();
        Long userId = orderQueryVo.getUserId();

        Long patientId = orderQueryVo.getPatientId();
        String patientName = orderQueryVo.getPatientName();


        String outTradeNo = orderQueryVo.getOutTradeNo();
        String orderStatus = orderQueryVo.getOrderStatus();
        String reserveDate = orderQueryVo.getReserveDate();
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();

        //条件构造
        LambdaQueryWrapper<OrderInfo> lqw = new LambdaQueryWrapper<>();
        lqw.like(keyword != null, OrderInfo::getHosname, keyword);
        lqw.like(patientName != null, OrderInfo::getPatientName, patientName);

        lqw.eq(userId != null, OrderInfo::getUserId, userId);
        lqw.eq(patientId != null, OrderInfo::getPatientId, patientId);
        lqw.eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus);
        lqw.eq(outTradeNo != null, OrderInfo::getOutTradeNo, outTradeNo);
        lqw.le(reserveDate != null, OrderInfo::getReserveDate, reserveDate);
        lqw.ge(createTimeBegin != null, OrderInfo::getCreateTime, createTimeBegin);
        lqw.le(createTimeEnd != null, OrderInfo::getCreateTime, createTimeEnd);

        //调用page方法
        Page<OrderInfo> pageModel = baseMapper.selectPage(pageParam, lqw);

        //参数编码转换
        pageModel.getRecords().forEach(this::packOrderInfo);

        //返回分页对象
        return pageModel;
    }

    //订单详情
    @Override
    public Map<String, Object> show(Long id) {
        Map<String, Object> map = new HashMap<>();

        OrderInfo orderInfo = this.packOrderInfo(this.getById(id));
        map.put("orderInfo", orderInfo);

        Patient patient =  patientFeignClient.getPatient(orderInfo.getPatientId());
        map.put("patient", patient);
        return map;
    }

    //取消预约订单
    @Override
    public Boolean cancelOrder(Long orderId) {
        //1.根据订单id获取订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);

        //2.判断当前时间 是否已经超过截止时间
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if (quitTime.isBeforeNow()){
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
        }

        //3.调用医院接口实现取消预约
            //获取密钥信息
            SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
            if(null == signInfoVo) {
                throw new YyghException(ResultCodeEnum.PARAM_ERROR);
            }

            //封装医院取消预约接口参数
            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("hoscode",orderInfo.getHoscode());
            reqMap.put("hosRecordId",orderInfo.getHosRecordId());
            reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
            String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
            reqMap.put("sign", sign);
            JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updateCancelStatus");

        //4.根据医院返回结果做不同处理
        if(result.getInteger("code") != 200){
            //抛出自定义异常
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }else {
            if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()){
                //调用微信退款方法
                Boolean isRefound = weixinService.refound(orderId);
                if (!isRefound){
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
                //更新订单表状态
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);

                //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());

                //短信提示
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
                Map<String,Object> param = new HashMap<String,Object>(){{
                    put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }};
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
                }
            return true;
            }
        }

    //就诊提醒
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        for(OrderInfo orderInfo : orderInfoList) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }

    }

    //包装参数
    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    //预约统计
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        //调用mapper方法得到数据
        List<OrderCountVo> orderCountVoList = baseMapper.selectOrderCount(orderCountQueryVo);

        //获取x所需要数据，日期list集合
        List<String> reserveDateList = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());

        //获取y轴所需数据，数量list集合
        List<Integer> countList = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());

        //封装数据到map集合
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("reserveDateList", reserveDateList);
        resultMap.put("countList", countList);

        //返回数据
        return resultMap;
    }
}